package org.example.lotterysystem.service.impl;

import org.example.lotterysystem.common.errorcode.ServiceErrorCodeConstants;
import org.example.lotterysystem.common.exception.ServiceException;
import org.example.lotterysystem.common.utils.CaptchaUtil;
import org.example.lotterysystem.common.utils.MailUtil;
import org.example.lotterysystem.common.utils.RedisUtil;
import org.example.lotterysystem.common.utils.RegexUtil;
import org.example.lotterysystem.service.VerificationCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.Random;

@Service
public class VerificationCodeServiceImpl implements VerificationCodeService {

    // 对于redis里面的key需要标准化：为了区分业务，应该给key定义前缀：
    // VerificationCode_13111111111:1233、User_13111111111:userInfo

    private static final String VERIFICATION_CODE_PREFIX = "VERIFICATION_CODE_";
    private static final Long VERIFICATION_CODE_TIMEOUT = 60L;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private MailUtil mailUtil;

    @Value(value = "${spring.mail.username}")
    private String from;
    @Autowired
    private JavaMailSender mailSender;

    @Override
    public void sendVerificationCode(String email){
        if (!RegexUtil.checkMail(email)) {
            throw new ServiceException(ServiceErrorCodeConstants.MAIL_ERROR);
        }
        //2.向邮箱发送验证码（集成邮件功能
        // 随机生成4位数字验证码
        String code = CaptchaUtil.getCaptcha(4);
        mailUtil.sendSampleMail(email,"登录验证码","验证码为"+code);

        // 调试
//        System.out.println("Storing to Redis with key: " + VERIFICATION_CODE_PREFIX + email);
//        System.out.println("Value to store: " + code);
//        boolean result = redisUtil.set(VERIFICATION_CODE_PREFIX + email, code, VERIFICATION_CODE_TIMEOUT);
//        System.out.println("Redis set operation result: " + result);

        //将验证码存放到redis中
        redisUtil.set(VERIFICATION_CODE_PREFIX + email, code, VERIFICATION_CODE_TIMEOUT);
    }

    @Override
    public String getVerificationCode(String email) {
        // 校验邮箱
        if (!RegexUtil.checkMail(email)) {
            throw new ServiceException(ServiceErrorCodeConstants.MAIL_ERROR);
        }
        return redisUtil.get(VERIFICATION_CODE_PREFIX + email);
    }
}
